#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <signal.h>


int main()
{
	int server_sockfd,client_sockfd;
	int server_len,client_len;
	struct sockaddr_in server_address;
	struct sockaddr_in client_address;

	char * hostname;
	/*
	 * 声明一些变量，服务器和客户端的套接字描述符,结构体和结构体的长度。
	 * */

	server_sockfd = socket(AF_INET,SOCK_STREAM,0);
	if (server_sockfd == -1) {
		perror("socket");
		exit(1);
	}

	//填充网络套接字结构体内容并关联此套接字至文件系统上面的一个文件名
	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = htonl(INADDR_ANY);
	server_address.sin_port = htons(3366);

	server_len = sizeof(server_address);
	bind(server_sockfd,(struct sockaddr*) &server_address,server_len);

	//创建一个连接队列，等待客户进行连接：
	listen(server_sockfd, 5);
	signal(SIGCHLD,SIG_IGN);
	while(1) {
		char ch;
		printf("server waiting\n");
		client_len = sizeof(client_address);
		client_sockfd = accept(server_sockfd,
				(struct sockaddr*) & client_address,&client_len);
		/*
		 * 得到一个套接字
		 * */
		if (fork() == 0) {
			hostname = inet_ntoa(client_address.sin_addr);
			printf("Welcome '%s'\n",hostname);
		
			read(client_sockfd,&ch,1);
			sleep(5);
			ch++;
			write(client_sockfd,&ch,1);
			close(client_sockfd);
			exit(0);
		}
		/*
		 * 使用fork创建子进程，在子进程中与客户端通信
		 * */
		else {
	//		close(client_sockfd);//为什么要close呢？
		}
	}


}
